package com.manolo.framework.connection.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import com.google.gson.Gson;
import com.manolo.framework.connection.entity.Player;
import com.manolo.framework.listener.dispatcher.DateDispatcher;

public class ClientMultiplayer implements Runnable {

	private int port;

	private int playerId = -1;

	private String ip;

	private BufferedReader in;

	private Socket socket = null;

	private PrintWriter out = null;

	private Player player;


	public ClientMultiplayer(String ip, int port, Player player) {
		this.port = port;
		this.ip = ip;
		this.player = player;
	}

	public void createConnection() throws Exception {
		// Create socket connection
		
			socket = new Socket(ip, port);
			/* TODO: alterado */
			// socket.setSoTimeout(1000);
			in = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));

	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			createConnection();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		while (playerId == -1) {
			try {
				if (playerId == -1) {
					String txt = in.readLine();
					Gson gson = new Gson();
					player = gson.fromJson(txt, Player.class);
					System.out.println("INIT"+gson.fromJson(txt, Player.class));
					
					playerId = player.getId();

				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		try {
			ClientPlayerSender runnableSender = new ClientPlayerSender(socket.getOutputStream(), player);
			Thread threadPlayerLister = new Thread(new ClientPlayerListener(socket, player));
			Thread threadPlayerSender = new Thread(runnableSender);
			threadPlayerSender.setName("sender-" + playerId);

			DateDispatcher.getInstance().addDateListener(runnableSender);

			threadPlayerLister.start();
			threadPlayerSender.start();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public Player getPlayer() {
		return player;
	}

	public void setPlayer(Player player) {
		this.player = player;
	}

}
